<?php
/**
 * 接口控制器基类
 * @copyright Copyright (c) 2014 wanthings.com
 * @author lizaifang <lizf@wanthings.com>
 */
class ApiController extends CController
{
    // disable layout
    public $layouts = '//layouts//main';

    // WARN!
    // if interface need user_id, please join it into $this->login_require;
    public $user_id = null;

    // this will be filled by app_id (client_id - app_id)
    public $app_id = 0;
    public $platform = 'ios';

    public $client_id = null;

    // store final output
    public $keep_result_object = false;
    public $params = array();
    public $result = null;
    public $errno = null;
    public $errmsg = null;
    public $status = array();
    public $shipper_type = 0;
    public $carry_type = 0;
    public $carry_id = 0; 
    public $is_driver = 0; 
    public $is_operation = 0; //是否操作员
    public $father_carry_id = 0;
    public $company_id = 0;
    public $have_cgm_role = 0; //子账号是否有货主端操作权限。
    // common errno and errmsg
    public $error_list = array(
        'success' => array('errno'=>0, 'errmsg'=>'success'),
        'error' => array('errno'=>1, 'errmsg'=>'unknown error'),
        'need_param' => array('errno' => 2, 'errmsg' => '参数不足'),
        'need_post' => array('errno'=>3, 'errmsg'=>'need post method'),
        'error_method' => array('errno'=>4, 'errmsg'=>'used wrong method'),
        'need_token' => array('errno'=>7, 'errmsg'=>'登录信息失效,请重新登录'),
        'error_param' => array('errno' => 6, 'errmsg' => '参数错误'),
        'illegl_token' => array('errno'=>7, 'errmsg'=>'登录信息失效,请重新登录'),
        'user_disabled' => array('errno'=>8, 'errmsg'=>'用户被禁用'),
        'user_not_exist' => array('errno' => 207, 'errmsg' => '用户不存在'),
    );
    public $self_error_list = array();
    // defined login require api name
    public $base_login_require = array();

    // defined all api for need user_id
    public $base_login_options = array();

    /**
     * 接口预处理
     *
     * @param object $action Yii action obejct
     *
     * @return boolean
     */
    public function beforeAction($action)
    {
        parent::beforeAction($action);
        $this->error_list = array_merge($this->error_list, $this->self_error_list);
        $this->status = $this->error_list['error'];

        // disable weblog
        // foreach (Yii::app()->log->routes as $route) {
        //     if ($route instanceof CWebLogRoute) {
        //         $route->enabled = false;
        //     }
        // }

        $action_id = $action->id;
        $controller_id = $action->controller->id; 
        
        $log = array();
        $log['url'] = $controller_id.'.'.$action_id; 
        $log['platform'] = Yii::app()->request->getParam('platform');
        $log['token'] = Yii::app()->request->getParam('token','');
        $log['role'] = Yii::app()->request->getParam('role','');
        file_put_contents(Yii::app()->getRuntimePath() . '/app_api_' . date("Y-m-d") . '.txt', sprintf("%s %s %s", date("Y-m-d H:i:s"), json_encode($log), PHP_EOL), FILE_APPEND);
        $this->app_id = Yii::app()->request->getParam('app_id');
        // 合并需要登录的action
        if (isset($this->login_require)) {
            $this->base_login_require = array_merge($this->base_login_require, $this->login_require);
        }

        // 合并可选登录的action
        if (isset($this->login_options)) {
            $this->base_login_options = array_merge($this->base_login_options, $this->login_options);
        }

        $this->platform = Yii::app()->request->getParam('platform');

        $cur_ca_id = implode('.', array(strtolower($controller_id), strtolower($action_id)));

        // if login option then use access_token trade user_id
        if (in_array($cur_ca_id, $this->base_login_options) || in_array($cur_ca_id, $this->base_login_require)) {
        // if (in_array($cur_ca_id, $this->base_login_require)) {
            $access_token = Yii::app()->request->getParam('token');
            if (!empty($access_token)) {

                # 如果是本系统维护用户数据 则需要下面的代码
                $user_id = UserToken::model()->getUserIdByToken($access_token);
                if (!empty($user_id)) {
                    // 获取正常状态的用户信息, 如果获取不到, 用户可能被禁用或者删除了, 这里就是被删除了
                    $user_info = User::model()->getBySid($user_id);
                    if (!empty($user_info['result']) && $user_info['result']['status'] == User::STATUS_NORMAL) {

                    } else {
                        $user_info = array();
                    }
                    if (empty($user_info)) {
                        // 如果该user_token的用户已被禁用
                        // if (in_array($cur_ca_id, $this->base_login_require)) {
                        //     $this->status = $this->error_list['user_disabled'];
                        //     $this->output();
                        //     return false;
                        // }
                    }
                $this->user_id = $user_id;
               
                $this->is_driver = User::model()->getIsDriver($this->user_id);

                $user = User::model()->getBySid($this->user_id);
                if($user['errno']==0){
                    $this->is_operation = $user['result']['is_operation'];
                    $this->have_cgm_role = $user['result']['have_cgm_role'];
                }
                
                $this->shipper_type = User::model()->getShipperTypeBySid($user_id);
                $this->carry_type = User::model()->getCarryTypeBySid($user_id);
                if($this->carry_type>0){
                    $this->carry_id = $user_id;
                }

                $this->father_carry_id = User::model()->getCarrySid($this->user_id);
                //自己的公司id ,如果既不是承运人，也不是货主。
                if($this->carry_type==0&&$this->shipper_type==0) {
                    $this->company_id = $this->father_carry_id;
                }else{
                    $this->company_id = $this->user_id;
                }

                } else if (in_array($cur_ca_id, $this->base_login_require)) {
                    // 如果user_token有错, 而且又需要登录, 则返回错误
                    $this->status = $this->error_list['illegl_token'];
                    $this->output();
                    return false;
                }
            } else if (in_array($cur_ca_id, $this->base_login_require)) {
                // 如果没有传user_token, 而且又需要登录, 则返回错误
                $this->status = $this->error_list['need_token'];
                $this->output();
                return false;
            }
        }
        return true;
    }


    /**
     * action执行完成之后自动输出报文
     */
    protected function afterAction($action)
    {
        $this->output();
    }

    /**
     * 输出报文
     */
    private function output()
    {
        header('Content-Type: application/json;');
        $result = array();
        $result = $this->status;
        if (!is_null($this->result)) {
            $result['result'] = $this->result;
        }
        if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
            if ($this->keep_result_object) {
                echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_FORCE_OBJECT);
            } else {
                echo json_encode($result, JSON_UNESCAPED_UNICODE);
            }
            ;
        } else {
            if ($this->keep_result_object) {
                echo json_encode($result, JSON_FORCE_OBJECT);
            } else {
                echo json_encode($result);
            }
        }
        return true;
    }

    public function getPost($name, $default = null)
    {
        return Yii::app()->request->getPost($name, $default);
    }

    public function getQuery($name, $default = null)
    {
        return Yii::app()->request->getQuery($name, $default);
    }
}
?>
